package main

import (
	"fmt"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var Db *gorm.DB

type Snowball struct {
	Id   int
	Code string
}

type StockWeek struct {
	SnowballId    int     `json:"snowball_id"`
	DayClosePrice float64 `json:"day_close_price"`
	DayDate       string  `json:"day_date"`
}

type StockWeekBuy struct {
	Code string `json:"code"`
}

func InitDb() {
	dsn := "root:Hadoop2860455122@tcp(47.114.163.161:3306)/user_xzdream?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("数据库连接失败!")
	}
	Db = db
}

func main() {
	InitDb()
	sb := []Snowball{}
	Db.Table("snowball").Find(&sb)

	for _, v := range sb {
		sw := []StockWeek{}
		Db.Table("stock_week").Where("snowball_id = ?", v.Id).Order("day_date desc").Limit(4).Find(&sw)
		dataLen := len(sw)
		if dataLen == 4 {
			if sw[0].DayClosePrice > sw[1].DayClosePrice && sw[1].DayClosePrice < sw[2].DayClosePrice && sw[2].DayClosePrice < sw[3].DayClosePrice {
				swb := StockWeekBuy{}
				swb.Code = v.Code
				Db.Table("stock_week_buy").Create(&swb)
			}
		} else if dataLen == 3 {
			if sw[0].DayClosePrice > sw[1].DayClosePrice && sw[1].DayClosePrice < sw[2].DayClosePrice {
				swb := StockWeekBuy{}
				swb.Code = v.Code
				Db.Table("stock_week_buy").Create(&swb)
			}
		} else {
			continue
		}
	}
}
